{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Download something\n",
    "\n",
    "**Introduce multiple ways to download something using python.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "os.makedirs('./img/', exist_ok=True)\n",
    "\n",
    "IMAGE_URL = \"https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## urlretrieve\n",
    "\n",
    "**Download the image url using urlretrieve.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('./img/image1.png', <http.client.HTTPMessage at 0x106640438>)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from urllib.request import urlretrieve\n",
    "urlretrieve(IMAGE_URL, './img/image1.png')      # whole document"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image1](/img/image1.png)\n",
    "## request download\n",
    "\n",
    "**Using requests.get to download at once.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "r = requests.get(IMAGE_URL)\n",
    "with open('./img/image2.png', 'wb') as f:\n",
    "    f.write(r.content)                      # whole document"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## download chunck by chunck\n",
    "\n",
    "**Set stream = True in get() function. This is more efficient.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = requests.get(IMAGE_URL, stream=True)    # stream loading\n",
    "\n",
    "with open('./img/image3.png', 'wb') as f:\n",
    "    for chunk in r.iter_content(chunk_size=32):\n",
    "        f.write(chunk)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
